package com.sensetime.mycamera;

import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;

import java.io.IOException;
import java.nio.ByteBuffer;

public class H264Encode {
    MediaCodec mediaCodec;
    private int width;
    private int height;
    int index; //当前第几帧
    private int frameCount = 20;//每秒多少帧

    public H264Encode(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public void startLive(){
        try {
            mediaCodec = MediaCodec.createEncoderByType("video/avc");
            MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", width, height);
            mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, width*height);
            mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE,frameCount);//每秒多少帧
            mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);//i帧的时间间隔
            mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
            mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);

            mediaCodec.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int encodeFrame(byte[] data) {
        //对数据进行编码
        int inputBufferIndex = mediaCodec.dequeueInputBuffer(10000);
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        if(inputBufferIndex>=0){
            ByteBuffer inputBuffer = mediaCodec.getInputBuffer(inputBufferIndex);

            inputBuffer.clear();
            inputBuffer.put(data);
            mediaCodec.queueInputBuffer(inputBufferIndex, 0, data.length, computPts(), 0);
            index++;
        }

        int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000);
        if(outputBufferIndex>=0){
            ByteBuffer outputBuffer = mediaCodec.getOutputBuffer(outputBufferIndex);
            byte[] buffer = new byte[bufferInfo.size];
            outputBuffer.get(buffer);
            FileUtils.write(buffer);
            FileUtils.writeContent(buffer);
            mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
        }
        return -1;
    }
    //1s == 1000毫秒 == 1000*1000微秒 ，1s有15帧，所有每一帧数据的pts可以计算
    //计算每一帧的顺序（pts值是多少，第一帧就是1000000/frameCount*1 第二帧就是1000000/frameCount*2）
    public int computPts(){
        return 1000000 / frameCount * index;
    }
}
